package org.design.thread.one;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * OrderService
 * CompletableFuture（复杂异步编排）
 * 适用场景：需要组合多个异步操作的复杂业务
 *
 * @author 樊温军
 * @date 2025/6/13 下午5:32
 */
@Service("orderServiceTask")
public class OrderService {

    @Async("taskExecutor")
    public CompletableFuture<Boolean> checkInventory(Long productId) {
        // 模拟库存检查
        return CompletableFuture.completedFuture(true);
    }

    @Async("taskExecutor")
    public CompletableFuture<Boolean> deductBalance(Long userId) {
        // 模拟扣款操作
        return CompletableFuture.completedFuture(true);
    }

    public void placeOrder(Long userId, Long productId) {
        CompletableFuture.allOf(
                checkInventory(productId),
                deductBalance(userId)
        ).thenRun(() -> {
            System.out.println("所有前置操作完成，开始创建订单");
            // 创建订单主逻辑
        });
    }
}

